<?php
/**
 *   OPENSHOP 公用AJAX函数库
 * 
 *   @link        http://baison.com.cn
 *   @copyright   Baison, Inc.
 *   @package     OpenShop
 *   @version     $Id: xajax.server.php,v 1.0 2009/06/17 08:36:58 created $
 *   @author      FillBag <fillbag@hotmail.com>
 */

function list_controls($arr_val, $p=1)
{
	global $smarty, $os, $db;	
	$objResponse = new xajaxResponse();
	if(is_array($arr_val['cat']) && sizeof($arr_val['cat'])>0)
	{
		$children = get_children_list($arr_val['cat']);
	}
	else
	{
		$children = get_children($arr_val['cat_id']);
	}
    extract(filter_controls($arr_val), EXTR_OVERWRITE);
	$goods_list = get_goods_list($arr_val['cat_id'], $children, $p, $sort, $order, $sql, $where);
	
	//
	$arr_ids = array();
	if(is_array($goods_list['list']))foreach ($goods_list['list'] as $k=>$g){
        array_push($arr_ids, $k);
	};
 	$objResponse->addScript("dis_items()");
	$sql = "SELECT DISTINCT g.cat_id FROM " . $os->table('goods_inventory') . " gi JOIN " . $os->table('goods') . 
	       " g ON gi.goods_id = g.goods_id WHERE " . 
	       " gi.goods_number_available > 0 AND g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 AND " . 
	       db_create_in($arr_ids, 'gi.goods_id');
	$arr_cates = $db->getCol($sql);	       
 	foreach ($arr_cates as $ca){
 		$objResponse->addAssign("cat_filter_".$ca,"disabled",false);
 	}
 		       
	$sql = "SELECT DISTINCT s.size_id FROM " . $os->table('goods_inventory') . " gi JOIN " . $os->table('goods') . 
	       " g ON gi.goods_id = g.goods_id LEFT JOIN " . $os->table('size') . " s ON gi.size_id = s.size_id WHERE " . 
	       " gi.goods_number_available > 0 AND g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 AND " . 
	       db_create_in($arr_ids, 'gi.goods_id');
	$arr_sizes = $db->getCol($sql);
 	foreach ($arr_sizes as $s){
 		$objResponse->addAssign("size_filter_".$s,"disabled",false);
 	}
 	
	$sql = "SELECT DISTINCT c.color_id FROM " . $os->table('goods_inventory') . " gi JOIN " . $os->table('goods') . 
	       " g ON gi.goods_id = g.goods_id LEFT JOIN " . $os->table('color') . " c ON gi.color_id = c.color_id WHERE " . 
	       " gi.goods_number_available > 0 AND g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 AND " . 
	       db_create_in($arr_ids, 'gi.goods_id');
	$arr_colors = $db->getCol($sql); 
 	foreach ($arr_colors as $c){
 		$objResponse->addAssign("color_filter_".$c,"disabled",false);
 	}	
    $smarty->assign('goods_list', $goods_list);
    $smarty->assign('filesync_host', $GLOBALS['filesync_host']);
    $smarty->assign('imageservice', $GLOBALS['_CFG']['pre_fetch_img']);
	$html = $smarty->fetch('library/goods_list_detail.lbi');
	$objResponse->addAssign('container_detail', 'innerHTML', $html);
	return $objResponse;
}

function get_children_list($arr_cat)
{
	$arr_all = array();
	if(!is_array($arr_cat))
	     return false;
	foreach($arr_cat as $cat)
	{
		$arr_all = array_unique(array_merge($arr_all, array_unique(array_merge(array($cat), array_keys(cat_list($cat, 0, false))))));			
	}
	return 'g.cat_id ' . db_create_in($arr_all);
}

function filter_controls($filter)
{	
	global $os;
    if((isset($filter['size']) && is_array($filter['size'])) || 
       (isset($filter['color']) && is_array($filter['color'])) || 
       (isset($filter['brand']) && is_array($filter['brand'])) || 
       (isset($filter['price_rule']) && !empty($filter['price_rule']))) {
		if(in_array('size', array_keys($filter)))
		{		
	            $sql .= " JOIN ".$os->table('goods_size')." gs ON g.goods_id=gs.goods_id AND ".db_create_in($filter['size'], 'gs.size_id');
		}
		
		if(in_array('color', array_keys($filter)))
		{		
				$sql .= " JOIN ".$os->table('goods_color')." gc ON g.goods_id=gc.goods_id AND ".db_create_in($filter['color'], 'gc.color_id');
		}
		
		if(in_array('brand', array_keys($filter)))
		{
				$where .= " AND ".db_create_in($filter['brand'], 'g.brand_id');
		}
		
		if(in_array('price_rule', array_keys($filter)) && !($filter['price_rule'] < 0))
		{
                $arr_price = explode('-', $filter['price_rule']);
                $min = $arr_price[0];
			    if ($min > 0)
			    {
			        $where .= " AND g.shop_price >= $min ";
			    }
			    $max = $arr_price[1];
			    if ($max > 0)
			    {
			        $where .= " AND g.shop_price <= $max ";
			    }
		}
    }
	$sort   = ' goods_id '; 
	$order  = ' DESC ';
	if(isset($filter['order_rule']) && in_array($filter['order_rule'], array('price_desc', 'price_asc'))){
		switch ($filter['order_rule']){
			default:break;
		    case 'price_desc':
	    		$sort  = ' shop_price '; 
	    		$order = ' DESC ';		    	
		    	break;
		    case 'price_asc':
	    		$sort  = ' shop_price '; 
	    		$order = ' ASC ';	
		    	break;
		}
	}
    unset($filter, $arr_price, $min, $max);
    return array('sql'   =>  $sql,  'where'  =>  $where, 'sort' => $sort, 'order' => $order);
}

function goto_page($page, $filter){
	global $smarty;
	$objResponse = new xajaxResponse();
	if(isset($filter['cat']) && sizeof($filter['cat'])>0){
		$children = get_children_list($filter['cat']);
	}else{
		$children = get_children($filter['cat_id']);
	}
	extract(filter_controls($filter), EXTR_OVERWRITE);
	$goods_list = get_goods_list($filter['cat_id'], $children, $page, $sort, $order, $sql, $where);
    $smarty->assign('goods_list', $goods_list);
    $smarty->assign('filesync_host', $GLOBALS['filesync_host']);
    $smarty->assign('imageservice', $GLOBALS['_CFG']['pre_fetch_img']);
	$html = $smarty->fetch('library/goods_list_detail.lbi');
	$objResponse->addAssign('container_detail', 'innerHTML', $html);
    //$objResponse->addScript("xajax_list_controls(".$filter.", ".$p.")");
	return $objResponse;
}


function get_goods_list($cat_id, $children, $page=1, $sort='goods_id', $order='DESC', $ext_sql='', $ext_where=''){	
	global $os, $_CFG;	
	class goodsListPage extends Page
	{
		function setData()
		{
			global $db, $sqlNum;
			$sqlNum++;
			$result = $db->query("set names utf8");
			$result = $db->query($this->page_stmt . " LIMIT " . $this->limit);
			$arr = array();		
			while ($row = $db->fetchRow($result))
			{
				$arr[$row['goods_id']]['goods_name']       = $GLOBALS['_CFG']['goods_name_length'] > 0 ? sub_str($row['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $row['goods_name'];			
	        	$arr[$row['goods_id']]['goods_thumb']      = get_image_path($row['goods_id'], $row['goods_thumb'], true);
				$arr[$row['goods_id']]['shop_price']       = price_format($row['shop_price']);
				$arr[$row['goods_id']]['url']              = build_uri('goods', array('gid'=>$row['goods_id']), $row['goods_name']);
			}
			return $arr;    						
		}	
	}
	$where      =   " LEFT JOIN " . $os->table('member_price') . " AS mp ON mp.goods_id=g.goods_id AND mp.user_rank = '$_SESSION[user_rank]'";
	$where     .=   " WHERE g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 AND ($children OR " . get_extension_goods($children) . ")";
    $sql        =   "SELECT g.goods_id, g.goods_name, g.goods_thumb, g.goods_img, IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS shop_price FROM ".
                    $os->table('goods')." g ";
    $sql   	   .=   $ext_sql;
    $where 	   .=   $ext_where;
	$sql        =   $sql . $where;    
	$sql       .=   " ORDER BY $sort $order";     
    $sql_count  =   'SELECT count(*) FROM '.$os->table('goods').' g '.$ext_sql.
                    " WHERE g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 AND ($children OR ". 
                    get_extension_goods($children) . ')';
    $sql_count .=   $ext_where;
    $size = isset($_CFG['page_size'])  && intval($_CFG['page_size']) > 0 ? intval($_CFG['page_size']) : 10;
	$goods_list = new goodsListPage($sql, $sql_count, $size);   	
	$goods_list->page = $page ? $page : 1;
	return $goods_list->getData();
}
?>